package shop.controller.manage.offline;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.common.dao.page.PagerModel;
import shop.core.util.QRcodeUtils;
import shop.services.manage.offline.OfflineService;
import shop.services.manage.offline.bean.Offline;
import shop.core.BaseController;
import shop.services.manage.organize.OrganizeService;
import shop.services.manage.organize.bean.Organize;
import shop.services.manage.system.bean.User;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 活动管理
 * Created by Administrator on 2017/4/15.
 */
@Controller
@RequestMapping("/manage/offline/")
public class OfflineAction extends BaseController<Offline> {
    @Autowired
    private OfflineService offlineService;
    @Autowired
    private OrganizeService organizeService;
    private static final String page_toList = "/manage/offline/offlineList";
    private static final String page_toEdit = "/manage/offline/offlineEdit";
    private static final String page_toAdd = "/manage/offline/offlineAdd";
    private static final String page_toDetails = "/manage/offline/offlineDetails";
    private static final String page_toCheckList = "/manage/offline/offlineCheckList";
    private static final String page_toCheckEdit = "/manage/offline/offlineCheckEdit";
    private static final String page_toCheckDetails = "/manage/offline/offlineCheckDetails";
    private static final String page_toAdminList = "/manage/offline/offlineAdminList";
    private static final String page_toAdminDetails = "/manage/offline/offlineAdminDetails";

    private OfflineAction() {
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }

    @Override
    public Services<Offline> getService() {
        return offlineService;
    }

    /**
     * 跳转到活动审核列表页面（admin）
     *
     * @return
     */
    @RequestMapping("toCheckList")
    public String toCheckList() {
        return page_toCheckList;
    }

    /**
     * 跳转到活动编辑页面（admin）
     *
     * @return
     */
    @RequestMapping("/toCheckEdit")
    public String toCheckEdit(@ModelAttribute(" offline") Offline offline, ModelMap model) throws Exception {
        offline = getService().selectOne(offline);
        model.addAttribute("e", offline);
        return page_toCheckEdit;
    }

    /**
     * 跳转到审核活动详情页面（admin）
     *
     * @return
     */
    @RequestMapping("toCheckDetails")
    public String toCheckDetails(@ModelAttribute(" offline") Offline offline, ModelMap model) throws Exception {
        offline = getService().selectOne(offline);
        model.addAttribute("e", offline);
        return page_toCheckDetails;
    }

    /**
     * 跳转到活动列表页面（admin）
     *
     * @return
     */
    @RequestMapping("toAdminList")
    public String toAdminList() {
        return page_toAdminList;
    }

    /**
     * 跳转到活动详情页面（admin）
     *
     * @param offline
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toAdminDetails")
    public String toAdminDetails(@ModelAttribute(" offline") Offline offline, ModelMap model) throws Exception {
        offline = getService().selectOne(offline);
        model.addAttribute("e", offline);
        return page_toAdminDetails;
    }

    /**
     * 跳转到活动详情页面（机构账号）
     *
     * @param offline
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toEdits")
    public String toEdits(@ModelAttribute(" offline") Offline offline, ModelMap model) throws Exception {
        offline = getService().selectOne(offline);
        model.addAttribute("e", offline);
        return page_toDetails;
    }

    /**
     * 发布活动
     *
     * @param request
     * @param offline
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "insertJsons", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJsons(HttpServletRequest request, @ModelAttribute("offline") Offline offline) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize organize = new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize = organizeService.selectOne(organize);
        offline.setOrganizeID(organize.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String date1 = sdf.format(new Date(date.getTime() + 1 * 24 * 60 * 60 * 1000));
        String date2 = sdf.format(new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000));
        String date3 = offline.getBeginTime();
        if(organize.getStatus().equals("1")){
            if (offline.getType().equals("1") && offline.getSend().equals("n")) {
                if(date3.compareTo(date1)>=0){
                    QRcodeUtils qrCodeUtils = new QRcodeUtils();
                    String contents = "contents";
                    offline.setQrCode(qrCodeUtils.createQrcode(request, contents));
                    offline.setStatus("2");
                    getService().insert(offline);
                    organize.setOfflineNum(organize.getAccountNum() + 1);
                    organizeService.update(organize);
                    return jsonResult;
                }else{
                    jsonResult.setMessage("请提前一天发布活动！");
                    jsonResult.setSuccess(false);
                    return jsonResult;
                }
            } else if (offline.getType().equals("1") && offline.getSend().equals("y")) {
                if (date3.compareTo(date2) > 0) {
                    offline.setStatus("1");
                    getService().insert(offline);
                    organize.setOfflineNum(organize.getAccountNum() + 1);
                    organizeService.update(organize);
                    return jsonResult;
                } else {
                    jsonResult.setMessage("请提前七天发布活动！");
                    jsonResult.setSuccess(false);
                    return jsonResult;
                }
            } else {
                if (date3.compareTo(date2) > 0) {
                    offline.setStatus("1");
                    getService().insert(offline);
                    organize.setOfflineNum(organize.getAccountNum() + 1);
                    organizeService.update(organize);
                    return jsonResult;
                } else {
                    jsonResult.setMessage("请提前七天发布活动！");
                    jsonResult.setSuccess(false);
                    return jsonResult;
                }
            }
        }else{
            jsonResult.setMessage("您还未通过审核，无法发布活动！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     *重新发布活动
     * @param request
     * @param offline
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "reIssueOfflineJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult reIssueOfflineJson(HttpServletRequest request, @ModelAttribute("offline") Offline offline) throws Exception {
        jsonResult = new JSONResult();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String date2 = sdf.format(new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000));
        String date3 = offline.getBeginTime();
        if(date3.compareTo(date2) > 0){
            offline.setStatus("1");
            getService().update(offline);
            return jsonResult;
        }else{
            jsonResult.setMessage("请提前七天发布活动！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }


    /**
     * 审核活动方法
     *
     * @param request
     * @param offline
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "checkOffline", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult checkOffline(HttpServletRequest request, @ModelAttribute("offline") Offline offline) throws Exception {
        jsonResult = new JSONResult();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String date2 = sdf.format(new Date(date.getTime() + 3 * 24 * 60 * 60 * 1000));
        Offline rs = new Offline();
        rs.setId(offline.getId());
        rs = offlineService.selectOne(rs);
        String date3 = rs.getBeginTime();
        if (date3.compareTo(date2) > 0) {
            QRcodeUtils qrCodeUtils = new QRcodeUtils();
            String contents = "contents";
            offline.setQrCode(qrCodeUtils.createQrcode(request, contents));
            getService().update(offline);
            return jsonResult;
        } else {
            offline.setStatus("5");
            getService().update(offline);
            jsonResult.setMessage("活动审核时间已过期，无法进行审核！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     * 分页获取数据列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @Override
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, Offline e) {
        int offset = 0;
        int pageSize = 10;
        if (e.getName() != null) {
            e.setPrincipal(e.getName());
        }
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize organize = new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize = organizeService.selectOne(organize);
        if (!user.getRid().equals("1")) {
            e.setOrganizeID(organize.getId());//机构账号查询所属活动
        } else {
        }
        PagerModel pager = getService().selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

}